package com.richapp.launcher.ui.activities;

import com.google.zxing.WriterException;
import com.richapp.launcher.R;
import com.richapp.launcher.database.system.dao.BoxModelDao;
import com.richapp.launcher.database.system.mode.BoxModel;
import com.richapp.launcher.utils.EncodingHandler;
import com.tencent.android.tpush.XGPushManager;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

public class CreateQRCodeActivity extends Activity {
	Intent intent = null;
	private ImageView iv_qr_image = null;
	public static final String CLOSEACTIVITYTAG = "com.richapp.launcher.closeactivity";
	private int qrcodelength;
	private String text = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		//设置全屏显示
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.create_qr_code);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(CLOSEACTIVITYTAG);
		registerReceiver(broadcastReceiver, intentFilter);
		iv_qr_image = (ImageView) findViewById(R.id.iv_qr_image);
		intent = getIntent();

        BoxModelDao boxModelDao = new BoxModelDao(this);
        BoxModel currentBox = boxModelDao.getCurrentBox();
		qrcodelength = displayMetrics.heightPixels/2;
		text = currentBox.getBoxCpuId()+"+"+currentBox.getBoxInsideIp();
		try {
			Bitmap qrCodeBitmap = EncodingHandler.createQRCode(text,qrcodelength);
			iv_qr_image.setImageBitmap(qrCodeBitmap);
		} catch (WriterException e) {
			e.printStackTrace();
		}
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onBackPressed() {
		CreateQRCodeActivity.this.finish();
	}

	@Override
	protected void onDestroy() {
		unregisterReceiver(broadcastReceiver);
		super.onDestroy();
	}

	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent == null)
				return;
			String action = intent.getAction();
			if (action.equals(CLOSEACTIVITYTAG)) {
				CreateQRCodeActivity.this.finish();
			}
		}
	};

	@Override
	protected void onResume() {
		super.onResume();
		XGPushManager.onActivityStarted(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		XGPushManager.onActivityStoped(this);
	}
}
